package com.zjmcollege.hotpot.ueditor;

import com.alibaba.fastjson.JSON;
import com.zjmcollege.hotpot.component.FileHandler;
import com.zjmcollege.hotpot.enums.FileType;
import com.zjmcollege.hotpot.exception.ServerException;
import com.zjmcollege.hotpot.exception.UploadFileIsEmpty;
import com.zjmcollege.hotpot.model.UploadResultModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * https://blog.csdn.net/kongbai953/Article/details/100933706
 *
 * https://www.656463.com/article/ueditorjzpzspringbootzhueditorjcs_9
 * https://www.cnblogs.com/han108/p/11377910.html
 * https://blog.csdn.net/lhmyy521125/article/details/88311938
 * @email 122162005@qq.com
 * @date 2019-11-06 17:49
 */
@RestController
@RequestMapping("/plugins/ueditor")
@Slf4j
public class UEditorController {
    @Autowired
    private FileHandler fileHandler;

    @RequestMapping("/config")
    @ResponseBody
    public String editor(@RequestParam("action") String action, MultipartFile upfile,
                         HttpServletRequest request, @RequestParam(value = "filepath",
            required = false)String filepath) {
        UEditorModel editor = new UEditorModel();
        editor.setState("服务端不支持");

        if (action != null & action.equals("config")) {
            String uConfigPath = "static\\plugins\\ueditor\\jsp\\config.json";
            StringBuffer config = new StringBuffer();
            try(
                    InputStream stream = this.getClass().getClassLoader()
                    .getResourceAsStream(uConfigPath);
                    BufferedReader reader = new BufferedReader(new
                            InputStreamReader(stream, "UTF-8"))
            ) {
                reader.lines().forEach(line -> {
                    log.debug(line);
                    config.append(line);
                });
            } catch (IOException e) {
                log.error(e.getLocalizedMessage());
            }

            return config.toString();
        } else if (action != null & action.equals("uploadimage") || action.equals("uploadscrawl")) {
                //{state：”数据状态信息”，url：”图片回显路径”，title：”文件title”，original：”文件名称”，···}
            if ("help".equals(filepath)) {
                return JSON.toJSONString(uploadFile(upfile, FileType.IMAGE));
            } else {
                return JSON.toJSONString(editor);
            }
        } else if("uploadfile".equals(action)) {
            return JSON.toJSONString(uploadFile(upfile, FileType.ATTACH));
        } else {
            return JSON.toJSONString(editor);
        }
    }

    /**
     * 上传文件
     * @param file
     * @param type 上传的文件的类型
     * @return
     */
    public UEditorModel uploadFile(MultipartFile file, FileType type) {
        UEditorModel editor = new UEditorModel();

        try {
            UploadResultModel resultModel = fileHandler.upload(file, type);
            editor.setState("SUCCESS");
            editor.setTitle(resultModel.getOriginal());
            editor.setUrl(resultModel.getUrl());
            editor.setOriginal(resultModel.getOriginal());
        } catch (UploadFileIsEmpty e) {
            e.printStackTrace();
            log.info(e.getLocalizedMessage());
            editor.setState("REFUSE:" + e.getMessage());
        } catch (ServerException e) {
            e.printStackTrace();
            log.info(e.getLocalizedMessage());
            editor.setState("ERROR:" + e.getMessage());
        } finally {
            return editor;
        }
    }
}
